import { COMMIT_CARD, DELETE_CARD, GET_CARDS } from "@/graphql/card";
import type { TBaseCard, TCardsQuery } from "@/utils/types";
import { useLazyQuery, useMutation, useQuery } from "@apollo/client";
import { message } from "antd";

export const useCards = (
  //   pageNum = 1,
  //   pageSize = DEFAULT_PAGE_SIZE
  courseId: string
) => {
  const { loading, data, refetch } = useQuery<TCardsQuery>(GET_CARDS, {
    variables: {
      courseId,
    },
  });

  return {
    loading,
    refetch,
    // page: data?.getCards.page,
    data: data?.getCards.data,
  };
};
export const useLazyCards = (
  //   pageNum = 1,
  //   pageSize = DEFAULT_PAGE_SIZE
  // courseId: string
) => {
  const [get,{data,loading}] = useLazyQuery<TCardsQuery>(GET_CARDS);
  const getCards=(courseId: string)=>{
    get({
      variables:{
        courseId
      }
    })
  }

  return {
    loading,
    getCards,
    // page: data?.getCards.page,
    data: data?.getCards.data,
  };
};

export const useEditCardInfo = (): [
  handleEdit: (
    id: string,
    params: TBaseCard,
    courseId: string,
    callback: () => void
  ) => Promise<void>,
  loading: boolean
] => {
  const [edit, { loading }] = useMutation(COMMIT_CARD);

  const handleEdit = async (
    id: string,
    params: TBaseCard,
    courseId: string,
    callback: () => void
  ) => {
    const res = await edit({
      variables: {
        id,
        params,
        courseId,
      },
    });
    if (res.data.commitCard.code === 200) {
      message.success(res.data.commitCard.message);
      callback();
      return;
    }

    message.error(res.data.commitCard.message);
  };

  return [handleEdit, loading];
};

export const useDeleteCard = (): [
  delHandler: (id: string, callback: () => void) => Promise<void>,
  loading: boolean
] => {
  const [del, { loading }] = useMutation(DELETE_CARD);

  const delHandler = async (id: string, callback: () => void) => {
    const res = await del({
      variables: {
        id,
      },
    });
    if (res.data?.deleteCard.code === 200) {
      message.info(res.data.deleteCard.message);
      callback();
      return;
    }
    message.info(res.data?.deleteCard.message);
  };

  return [delHandler, loading];
};
